package router

import (
	"context"
	"errors"
	"log"
	"net/http"

	"time"

	"gin-gateway/core/init"
)

var HttpSrvHandler *http.Server

func HttpProxyServerRun() {
	HttpSrvHandler = &http.Server{
		Addr:           Init.GetStringConf("proxy.http.addr"),
		Handler:        InitProxyRouter(),
		ReadTimeout:    time.Duration(Init.GetIntConf("proxy.http.read_timeout")) * time.Second,
		WriteTimeout:   time.Duration(Init.GetIntConf("proxy.http.write_timeout")) * time.Second,
		MaxHeaderBytes: 1 << uint(Init.GetIntConf("proxy.http.max_header_bytes")),
	}
	log.Printf("[INFO] HttpProxyServerRun %s\n", Init.GetStringConf("proxy.http.addr"))
	if err := HttpSrvHandler.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatalf("[ERROR] HttpProxyServerRun %s err:%v\n", Init.GetStringConf("proxy.http.addr"), err)
	}
}

func HttpProxyServerStop() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := HttpSrvHandler.Shutdown(ctx); err != nil {
		log.Printf("[ERROR] HttpProxyServerStop err:%v\n", err)
	}
	log.Printf("[INFO] HttpProxyServerStop %v stopped\n", Init.GetStringConf("proxy.http.addr"))
}
